//
//  LGMedicineBallSearchController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/24.
//

#import "LGMedicineBallSearchController.h"
#import "LGMedicineBallDetailController.h"
#import "LGMedicineBallPatientCell.h"
#import "LGSearchRecordCell.h"
@interface LGMedicineBallSearchController ()<UITableViewDataSource,UITableViewDelegate,LGMedicineBallPatientDelegate>
/**   */
@property (nonatomic , strong)UIView *topView;
/**   */
@property (nonatomic , strong)UITextField *searchTF;
/**   */
@property (nonatomic , strong)UIView *leftView;
/**   */
@property (nonatomic , strong)UIButton *cancelBtn;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UITableView *recordTableView;
/**   */
@property (nonatomic , strong)NSMutableArray *recordArray;
/**   */
@property (nonatomic , strong)NSMutableArray *dataArray;
/**   */
@property (nonatomic , copy)NSString *pageNo;
@end

@implementation LGMedicineBallSearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isfirst = NO;
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
    [self createSearchView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.recordTableView];
    [self emptyViewWithSuperView:self.view frame:self.tableView.frame];
    [self.emptyView stopBufferAction];
    [self requestRecordData];
}
-(void)requestData{
    self.pageNo = @"1";
    self.dataArray = [NSMutableArray array];
    [self requestMoreData];
}

-(void)requestMoreData{
    [RequestUtil withPOST:@"/doctor/patient.dcb.patient/pagedList" parameters:@{@"pageNo":self.pageNo,@"pageSize":@"20",@"keyword":self.searchTF.text,@"datasource":self.datasource} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if(code == 200){
//            self.countLabel.text = [NSString stringWithFormat:@"运动方案：%@个",returnData[@"total"]];
            NSArray *tempArray = returnData[@"data"];
            if(tempArray.count>0){
                self.pageNo = [NSString stringWithFormat:@"%ld",[returnData[@"current_page"] integerValue]+1];
                [self.dataArray addObjectsFromArray:tempArray];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:0];
        }
    }];
}


-(void)requestRecordData{
    NSArray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"searchPatientRecord"];
    self.recordArray = [NSMutableArray arrayWithArray:tempArray];
    [self.recordTableView reloadData];
}


//取消
-(void)cancelSearchAction{
    [self.navigationController popViewControllerAnimated:YES];
}

//清空所有搜索记录
-(void)clearAllSearchRecord{
    [self.recordArray removeAllObjects];
    [self.recordTableView reloadData];
    [[NSUserDefaults standardUserDefaults] setObject:self.recordArray forKey:@"searchPatientRecord"];
}
//删除搜索记录
-(void)deleteSearchRecord:(UIButton *)sender{
    NSInteger index = sender.tag-1000;
    [self.recordArray removeObjectAtIndex:index];
    [self.recordTableView reloadData];
    [[NSUserDefaults standardUserDefaults] setObject:self.recordArray forKey:@"searchPatientRecord"];
}

//忽略
-(void)ignoreDataAction:(NSString *)planid index:(NSInteger)index{
    __block NSInteger currentIndex = index;
    [RequestUtil withPOST:@"/doctor/patient.dcb.patient/ignore" parameters:@{@"plan_id":planid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMedicinBallData" object:nil];
            [self.dataArray removeObjectAtIndex:currentIndex];
            [self.tableView reloadData];
        }else{
            [TooltipView showMessage:message offset:0];
        }
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:@"忽略失败，请重试" offset:0];
    }];
}

-(void)textFieldEditingChanged:(UITextField *)textField{
    NSString *lang = textField.textInputMode.primaryLanguage;// 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]){
        UITextRange *selectedRange = [textField markedTextRange];
        if (!selectedRange) { // 没有高亮
            NSLog(@">>???>>>%@",textField.text);
            
            if(textField.text.length == 0){
                [self.emptyView stopBufferAction];
                self.recordTableView.hidden = NO;
                [self.recordTableView reloadData];
            }else{
                [self requestData];
                self.recordTableView.hidden = YES;
            }
        }
    }else{
        if(textField.text.length == 0){
            [self.emptyView stopBufferAction];
            self.recordTableView.hidden = NO;
            [self.recordTableView reloadData];
        }else{
            [self requestData];
            self.recordTableView.hidden = YES;
        }
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == self.tableView){
        return self.dataArray.count;
    }else{
        return self.recordArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableView){
        LGMedicineBallPatientCell *patientCell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        patientCell.selectionStyle = UITableViewCellSelectionStyleNone;
        patientCell.dataDic = self.dataArray[indexPath.row];
        patientCell.delegate = self;
        return patientCell;
    }else{
        LGSearchRecordCell *recordCell = [tableView dequeueReusableCellWithIdentifier:@"recordCell" forIndexPath:indexPath];
        recordCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [recordCell.deleteBtn addTarget:self action:@selector(deleteSearchRecord:) forControlEvents:UIControlEventTouchUpInside];
        recordCell.deleteBtn.tag = indexPath.row + 1000;
        recordCell.content = self.recordArray[indexPath.row];
        return recordCell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableView){
        NSDictionary *tempDic = self.dataArray[indexPath.row];
        NSString *realname = LGNSString(tempDic[@"patient_name"]);
        if(![self.recordArray containsObject:realname]){
            [self.recordArray addObject:realname];
            [[NSUserDefaults standardUserDefaults] setObject:self.recordArray forKey:@"searchPatientRecord"];
        }

        LGMedicineBallDetailController *controller = [[LGMedicineBallDetailController alloc] init];
        controller.operatName = LGNSString(tempDic[@"plan_type_name"]);
        controller.planid = LGNSString(tempDic[@"plan_id"]);
        controller.planType = LGNSString(tempDic[@"type"]);
        [self.navigationController pushViewController:controller animated:YES];
        
    }else{
        NSString *content = self.recordArray[indexPath.row];
        self.searchTF.text = content;
        [self textFieldEditingChanged:self.searchTF];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.001)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.001)];
}

#pragma mark
#pragma mark ====> 创建控件
-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGMedicineBallPatientCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithString:@"#F2F3F5"];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
    }
    return _tableView;
}

-(UITableView *)recordTableView{
    if(!_recordTableView){
        _recordTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight) style:UITableViewStylePlain];
        [_recordTableView registerClass:[LGSearchRecordCell class] forCellReuseIdentifier:@"recordCell"];
        _recordTableView.backgroundColor = [UIColor colorWithString:@"#F9F9F9"];
        _recordTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _recordTableView.showsVerticalScrollIndicator = NO;
        _recordTableView.rowHeight = viewPix(36);
        _recordTableView.dataSource = self;
        _recordTableView.delegate = self;
        _recordTableView.tableHeaderView = [self recordHeaderView];
    }
    return _recordTableView;
}

-(UIView *)recordHeaderView{
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(46))];
    UILabel *titleLabel = [UILabel lableWithText:@"历史搜索记录" colorString:@"#666666" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
    titleLabel.frame = CGRectMake(viewPix(16), 0, viewPix(150), viewPix(46));
    [baseView addSubview:titleLabel];
    
    UIButton *deleteBtn = [UIButton buttonWithImage:@"患者搜素-清空记录" selectImage:@"患者搜素-清空记录"];
    deleteBtn.frame = CGRectMake(Screen_W-viewPix(42), viewPix(5), viewPix(36), viewPix(36));
    [deleteBtn addTarget:self action:@selector(clearAllSearchRecord) forControlEvents:UIControlEventTouchUpInside];
    [baseView addSubview:deleteBtn];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(46)-0.5, Screen_W-viewPix(32), 0.5)];
    lineView.backgroundColor = [UIColor colorWithString:@"#E1E1E1"];
    [baseView addSubview:lineView];
    return baseView;
}




-(UIButton *)cancelBtn{
    if(!_cancelBtn){
        _cancelBtn = [UIButton buttonWithTitle:@"取消" titleFont:LGFontWeight(14, UIFontWeightMedium) textColor:@"#429BFF" imageName:@""];
        _cancelBtn.frame = CGRectMake(Screen_W-viewPix(60), statusBarHeight+6, viewPix(60), 32);
        [_cancelBtn addTarget:self action:@selector(cancelSearchAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

-(UITextField *)searchTF{
    if(!_searchTF){
        _searchTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(12), statusBarHeight+6, Screen_W-viewPix(72), 32)];
        _searchTF.backgroundColor = [UIColor colorWithString:@"#F3F3F3"];
        _searchTF.cornerRidus = 5;
        _searchTF.tintColor = [UIColor colorWithString:@"#333333"];
        _searchTF.textColor = [UIColor colorWithString:@"#333333"];
        _searchTF.textAlignment = NSTextAlignmentLeft;
        _searchTF.keyboardType = UIKeyboardTypeDefault;
        _searchTF.returnKeyType = UIReturnKeySearch;
        _searchTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTF.placeholder = @"输入患者关键信息搜索";
        _searchTF.font = LGFont(15);
        _searchTF.delegate = self;
        _searchTF.leftViewMode = UITextFieldViewModeAlways;
        _searchTF.leftView = [self leftView];
        [_searchTF addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTF;
}

-(UIView *)leftView{
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewPix(36), 32)];
    UIImageView *searchIcon = [[UIImageView alloc]initWithFrame:CGRectMake(viewPix(12), 8, 16, 16)];
    searchIcon.image = [UIImage imageNamed:@"searchGray16"];
    [leftView addSubview:searchIcon];
    return leftView;
}

-(void)createSearchView{
    UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, topBarHeight)];
    baseView.backgroundColor = [UIColor whiteColor];
    [baseView addSubview:self.searchTF];
    [baseView addSubview:self.cancelBtn];
    [self.view addSubview:baseView];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
